<?php

namespace Payment\Model;

use Common\Model\BaseModel;
use Common\Model\ModelException;

class PaymentModel extends BaseModel {

    protected $_auto = [
        ['created_at', 'time', self::MODEL_INSERT, 'function'],
    ];
    protected $_validate = [
    ];
    protected $_scope = [];

    /**
     * 发红包
     */
    public function setLuckMoney($uid, $params) {
        try {
            $Luckmoney = D('Luckmoney');
            if (!empty($params['type']) && $params['type'] == 2) {
                $data['group_id'] = $params['group_id']; //群id
                $data['sort'] = $params['sort']; //1， 随机红包 2，普通红包
                $data['num'] = $params['num'];
                if ($params['sort'] == 1) {//随机红包
                    $min = 0.01; //最小的红包金额
                    if ($params['money'] / $params['num'] < $min) {
                        throw new ModelException(30006, '随机红包单个最小不能低于0.01');
                    }
                    $rand = $this->makehongbao($params['money'], $params['num']);
                    if (in_array(0, $rand)) {
                        $max_index = array_search(max($rand), $rand);
                        $min_index = array_search(min($rand), $rand);
                        $rand[$max_index] = $rand[$max_index] - 0.01;
                        $rand[$min_index] = $rand[$min_index] + 0.01;
                    }
                    $data['ranking'] = implode('|', $rand);
                }
            }

            $data['user_id'] = $uid;
            $data['money'] = $params['money'];
            $data['type'] = $params['type'];
            $data['remark'] = $params['remark'];
            $data['whose'] = $params['whose']; //谁得到
            $data['remain_money'] = $params['money'];
            $data['create_time'] = time();

            //*增加一个金钱记录
            $UsersModel = D('Account/Users');
            $result = $UsersModel->costMoney($uid, 'cut_luckmoney', $params['money'] * 100, '发红包', 'money');
            if ($result) {
                return $Luckmoney->add($data);
            }
        } catch (Exception $ex) {
            
        }
    }

    /* 普通随机红包 */

    private function randMoney($sum, $count) {
        $arr = [];
        $hes = 0;
        $hess = 0;
        for ($i = 0; $i < $count; $i++) {
            $rand = rand(1, 1000);
            $arr[] = $rand;
            $hes+=$rand;
        }
        $arr2 = [];
        foreach ($arr as $key => $value) {
            $round = round(($value / $hes) * $sum, 2);
            $arr2[] = $round;
            $hess+=$round;
        }
        if ($sum != round($hess, 2)) {
            $hesss = round($sum - $hess, 2);
            $arr2[0] = $arr2[0] + $hesss;
        }
        return $arr2;
    }

    function makehongbao($money = 1, $num = 1) {
        $min = 0.01;
        $average = $money / $num;
        try {

            $arr = []; //存所有的红包
            if ($num == 1) {
                $arr[] = $money;
                return $arr;
            }
            $em = $money - $min * $num; //剩余金额 
            if ($em == 0) {
                for ($i = 0; $i < $num; $i++) {
                    $arr[] = $min;
                }
            } else {
                $tt = $num; //剩余没分配金额的红包的数量
                $total = 0;
                for ($i = 0; $i < $num; $i++) {
                    //当是还剩最后一个红包时 把剩下的钱装进去
                    if ($tt == 1) {
                        $h = $em;
                    } else {
                        if ($i < ((int) $num / 3)) {
                            $h = $this->randomFloat($min, $em / $tt * 2);
                        } else {
                            $h = $this->randomFloat($min, $em / $tt);
                        }
                    }
                    $em = $em - $h;
//                    $arr[] = sprintf("%.2f", $h + $min);
                    $arr[] = round($h + $min, 2);
                    $tt--;
                }
            }
            if (max($arr) > $average * 2) {
                $arr = $this->average($arr, $money, $num);
            }
            shuffle($arr);
//            pr(array_sum($arr));
//            pr($arr);
            return $arr;
        } catch (ModelException $e) {
            throw $e;
        }
    }

    function average($param, $money, $num) {
        $average = $money / $num;
        $jj = 0;
        while (max($param) > $average * 2) {
            sort($param);
            $param[$num - 1] -= $average;
            $param[$num - 1] = round($param[$num - 1],2);
            $param[$jj]+=$average;
            $param[$jj] = round($param[$jj],2);
            $jj++;
        }
        return $param;
    }

    function randomFloat($min = 0, $max = 1) {
        return sprintf("%.2f", $min + mt_rand() / mt_getrandmax() * ($max - $min));
    }

    /*
     * 收红包
     */

    public function getLuckMoney($uid, $id) {
        M()->startTrans();
        $redis = redis();
//        S($id,NULL);
//        $redis->srem('luckmoney'.$id,$uid);
        $LuckmoneyM = D('Luckmoney');
        $LuckmoneyLogM = D('LuckmoneyLog');
        $luckmoney = $LuckmoneyM->lock(true)->find($id);
        //先检查红包过期
        if ($luckmoney['create_time'] + 60 * 60 * 24 < time()) {
            return ['code' => '110032', 'message' => '红包已过领取时间'];
        }
        //检查红包领完没
        if ($luckmoney['status'] == 2) {
            return ['code' => '110031', 'message' => '红包已领完'];
        }

        $is_over = false;
        if ($luckmoney['type'] == 2) {//1 一对一发红包，2一对多发
            //群红包要检查我没有领取权限
            $whose = explode(',', $luckmoney['whose']);
            if (!in_array($uid, $whose)) {
                return ['code' => '110034', 'message' => '你不在领取红包资格内'];
            }
            $count = S($id) ? S($id) : '0';
            if ($count == $luckmoney['num']) {
                return ['code' => '110031', 'message' => '红包已领完'];
            }

            if ($redis->sismember('luckmoney' . $id, $uid)) {
                return ['code' => '110031', 'message' => '你已经领取过红包了'];
            }
            if ($luckmoney['sort'] == 1) {//1， 随机红包 2，普通红包
                $ranking = explode('|', $luckmoney['ranking']);
                $luckmoney['money'] = $ranking[$count];
                S($id, $count + 1);
                $key = 'luckmoney' . $id;
                $redis->sAdd($key, $uid);
            } else {
                $luckmoney['money'] = $luckmoney['money'] / $luckmoney['num'];
            }
            if ($luckmoney['num'] <= $count + 1) {
                $is_over = true; //变更红包状态
            }
        } else {
            //防止自己领，加不必要的判断
            if ($luckmoney['user_id'] == $uid) {
                return ['code' => '200', 'message' => '不能领取自己发的红包'];
            }
            $is_over = true; //变更红包状态
        }
        $data = [
            'luckmoney_id' => $id,
            'luck_people' => $uid,
            'luck_money' => $luckmoney['money'],
            'type' => $luckmoney['type'],
            'sort' => $luckmoney['sort'],
            'user_id' => $luckmoney['user_id'],
            'create_time' => time()
        ];

        try {
            //*增加一个金钱记录
            $UsersModel = D('Account/Users');
            $res1 = $UsersModel->earnMoney($uid, 'get_luckmoney', $luckmoney['money'] * 100, '抢红包', '', $luckmoney['user_id']);
            //*增加一个金钱记录

            if (!empty($res1)) {
                $LuckmoneyLogM->lock(true)->add($data);
                $Luckmoneydata['remain_money'] = $luckmoney['remain_money'] - $luckmoney['money'];
                if ($is_over) {
                    $Luckmoneydata['status'] = 2;
                }
                $res3 = $LuckmoneyM->where(['luckmoney_id' => $id])->setField($Luckmoneydata);
                if ($res3) {
                    M()->commit();
                    return ['code' => '200', 'message' => '领取成功'];
                }
            }
            M()->rollback();
            return FALSE;
        } catch (Exception $exc) {
            $LuckmoneyLogM->rollback();
            return FALSE;
        }
    }

    /*
     * 聊吧app充值
     */

    public function deal($callbackData) {
        $chanrgeModel = D('PaymentLog');
        $payment = $chanrgeModel->getByPaymentNo($callbackData['orderId']);
        if ($payment && $payment['status'] == 'unpaid') {
            $UsersModel = D('Account/Users');
            $ret = $UsersModel->earnMoney($payment['uid'], 'charge', $payment['amount'], '零钱充值', '');
            if ($ret) {
                $chanrgeModel->where(['id' => $payment['id']])->setField(['status' => 'paid', 'update_time' => time()]);
            }
            return TRUE;
        }
    }

    protected function _after_find(&$record, $options) {
        if (isset($record['pic'])) {
            $record['pic'] = auto_prefix($record['pic']);
        }
        if (isset($record['whose'])) {
            $record['whose'] = $record['whose'] ? json_decode($record['whose']) : '';
        }
        if (isset($record['remark'])) {
            $record['remark'] = $record['remark'] ? $record['remark'] : '';
        }
    }

    protected function _after_select(&$records, $options) {
        foreach ($records as &$record) {
            $this->_after_find($record, $options);
        }
    }

}
